using System;

namespace Tycho.Parser.Peg {
    public class IdentifierKeywordProduction : Production {
        public string Keyword;
        private readonly IProduction IdentifierProduction;

        public IdentifierKeywordProduction (string keyword) : this (keyword, new IdentifierProduction ()) {}

        public IdentifierKeywordProduction (string keyword, IProduction identifierProduction) {
            Keyword = keyword;
            IdentifierProduction = identifierProduction;
            Name = "'" + Keyword + "'";
            ErrorInformation = new KeywordErrorInformation (Keyword);
        }

        public static Terminal CreateTerminal (string keyword) {
            return new Terminal (new IdentifierKeywordProduction (keyword));
        }

        protected override ParseResult ReallyParse (char[] source, int index, ParseContext context, string sourceString, ParseEnvironment parseEnvironment) {
            ParseResult result = IdentifierProduction.Parse (source, index, context, sourceString, parseEnvironment);
            
            if (result != null) {
                var term = result.Term as IdentifierTerm;

                if (term != null && term.Name == Keyword) {
                    return new ParseResult (result.Index, null, result.Context);
                }
            }

            return null;
        }
    }
}